(function(angular) {
	'use strict';
	angular.module('fs.waf').controller('cda.classification.updateContinueController', updateContinueController);
	updateContinueController.$inject = [ '$scope', '$q', 'Constants', 'modalService', 'gridService', 'layoutConfig', 'validatorConfig', 'authService',
	                                      'classificationService', 'arithService' ];
	function updateContinueController($scope, $q, Constants, modalService, gridService, layoutConfig, validatorConfig, authService, 
			classificationService, arithService) {
		var ctrl = this, params = $scope.$stateParams.params, errorMessage = {};
		var log = $scope.loggerFactory.getLogger("classificationCreateContinue");
		ctrl.layoutConfig = layoutConfig;
		ctrl.validatorConfig = validatorConfig;
		ctrl.classification = {};
		
		ctrl.init = function() {
			if(ctrl.validatorConfig) ctrl.layoutConfig.formConfigs.propClassifi.tableConfigs.table.validatorConfig = ctrl.validatorConfig.classifiList;
			ctrl.propClassifiInnerGridOptions = gridService.createInnerGridOptions($scope, ctrl.layoutConfig.formConfigs.propClassifi.tableConfigs.table, rowSelectionChanged);
			ctrl.propClassifiInnerGridOptions.data = 'vm.classification.classifiList';
			
			authService.updateContinue(params).then(function(response) {
				if (response.data && response.data.model && response.data.task) {
					ctrl.classification = response.data.model;
					ctrl.classification.classifiList = ctrl.classification.classifiList || [];
					ctrl.classification.classifiList.siteCode = ctrl.classification.siteCode;
					ctrl.classification.classifiList.siteName = ctrl.classification.siteName;
					ctrl.classification.dataStatus = params.dataStatus || 'V';
					ctrl.classification.taskId = response.data.task.taskId;
				}
			});
		};
		
		function rowSelectionChanged(eventRow, selectedRows) {
			ctrl.selectedClassifications = selectedRows;
		}
		
		ctrl.changeStatus = function(obj, form){
			if(form.$dirty && 'V' == obj.dataStatus) obj.dataStatus = 'U';
		};
		
		ctrl.uniqueCheck = function (obj, form) {		//obj currentObj
			if (form.$dirty && ctrl.classification.classifiList != null && ctrl.classification.classifiList.length >0 ){
				ctrl.classification.classifiListCheck = angular.copy(ctrl.classification.classifiList); 
				var newAddedLength = ctrl.classification.classifiListCheck.length;
				ctrl.classification.classifiListCheck.splice(newAddedLength-1, 1);
				var count = 0;
				for ( var i=0; i<ctrl.classification.classifiListCheck.length;i++){
					if ( ctrl.classification.classifiListCheck[i].classificationName == obj.classificationName ){
						count ++;
						obj.classificationName = null;
					} 
				}
				if ( count >0){
					modalService.openErrorDialogs({
						'messages' : [ "js.info.common.item-hadbeen-existed"]
					});
					
				}
			}
		};
		
		ctrl.addClassifi = function() {
			return $q(function(resolved, rejected){
				var messages = [];
				var msg1 = validateClassiFi(ctrl, false);
				if (msg1) messages.push(msg1);
				if (messages && messages.length > 0) {
					modalService.openErrorDialogs({
						'messages' : messages
					});
					return;
				}	
				if (!ctrl.classification.classifiList) {
					ctrl.classification.classifiList = [];
				}
				var classifiCondFrom;
				var classifiCond;
				var dataStatus;
				if (ctrl.classification.classifiList.length == 0) {
//					classifiCond = 0;
//					classifiCondFrom = 0;
				} else {
					var preCondTenor = ctrl.classification.classifiList[ctrl.classification.classifiList.length - 1].classifiCond;
					classifiCondFrom = arithService.add(preCondTenor, 1);
				}
				ctrl.classification.classifiList.push({
					classifiCondFrom : classifiCondFrom,
					classifiCond : classifiCond,
					dataStatus : 'C'
				});
				rejected();
			});
		};
		

		ctrl.removeClassifi = function() {
			return $q(function(resolved, rejected){
				angular.forEach(ctrl.selectedClassifications, function(selectedClassifi, key) {
					if ( selectedClassifi.dataStatus != null && (selectedClassifi.dataStatus == 'V'
						|| selectedClassifi.dataStatus == 'U') ) {
						modalService.openErrorDialogs({
							'messages' : [ "js.info.common.item-verified-cannotbe-deleted"]
						});
					} else {
						angular.forEach(ctrl.classification.classifiList, function(classifi, index) {
							if (classifi.$$hashKey == selectedClassifi.$$hashKey) {
								ctrl.classification.classifiList.splice(index, 1);
							}
						});
					}
				});
				//
				if (ctrl.classification.classifiList && ctrl.classification.classifiList.length > 0) {
					ctrl.classification.classifiList[0].classifiCondFrom = 0;
				}
				rejected();
			});
			
		};
		
		//sort classificationList by classifiCondFrom
		function compare(property){
		    return function(a,b){
		        var value1 = a[property];
		        var value2 = b[property];
		        return value1 - value2;
		    };
		};
		
		function validateClassiFi(ctrl, isFinalCheck) {
			if (isFinalCheck && (!ctrl.classification.classifiList || ctrl.classification.classifiList.length == 0)) {
				var msg = 'Classification is Required.';
				return msg;
			}
			if (ctrl.classification.classifiList && ctrl.classification.classifiList.length >0) {
				ctrl.classification.classifiList = ctrl.classification.classifiList.sort(compare('classifiCondFrom'));
				var lastCondition;
				//last classifi
				var classi = ctrl.classification.classifiList[ctrl.classification.classifiList.length -1];
				if ( !classi.classifiCond && !isFinalCheck ){
					var msg = '"To Classification Condition (included)" is Required in row ' + (ctrl.classification.classifiList.length);
					return msg;
				} else {
					for (var i = 0; i < ctrl.classification.classifiList.length; i++) {
						var classifi = ctrl.classification.classifiList[i];
						var classifiCondFrom = classifi.classifiCondFrom;
						var classifiCond = classifi.classifiCond;
						
						if (!classifi.classificationName) {
							var msg = '"Classification Name" is Required in row ' + (i+1);
							return msg;
						}
						if (!classifi.loanLossPct) {
							var msg = '"Loan Loss Percent Rate (%)" is Required in row ' + (i+1);
							return msg;
						}
						if (i == 0) {
							lastCondition = classifiCond;
						}else{
							var currTenerFromNeedValue = arithService.add(lastCondition, 1);
							if (!arithService.eq(classifiCondFrom, currTenerFromNeedValue)) {
								var msg = '"From Classification Condition (included)" must be equal previous "To Classification Condition (included)" + 1 in row ' + (i+1);
								return msg;
							}
						}
						if (!classifiCond){
							if (i == ctrl.classification.classifiList.length-1){
								lastCondition = ctrl.classification.classifiList[i-1].classifiCond;
								var currTenerFromNeedValue = arithService.add(lastCondition, 1);
								if (!arithService.eq(classifiCondFrom, currTenerFromNeedValue)) {
									var msg = '"From Classification Condition (included)" must be equal previous "To Classification Condition (included)" + 1 in row ' + (i+1);
									return msg;
								} else {
									return;
								}
							} else {
								var msg = '"To Classification Condition (included)" is Required in row ' + (i+1);
								return msg;
							}
						} else if (arithService.lt(classifiCond, classifiCondFrom)){
							var msg = '"To Classification Condition (included)" should be bigger than or equal to "From Classification Condition (included)" in row ' + (i+1);
							return msg;
						}
						lastCondition = classifiCond;
					}
				}
				
			}
		}

		ctrl.updateContinueSave = function() {
			var messages = [];
			var msg1 = validateClassiFi(ctrl, true);
			if (msg1) messages.push(msg1);
			if (messages && messages.length > 0) {
				modalService.openErrorDialogs({
					'messages' : messages
				});
				return;
			}
			log.debug('prop in classification:');
			for (var name in ctrl.classification) {
				log.debug(name + '=' + ctrl.classification[name]);
			}
			return authService.updateContinueSave(ctrl.classification).then(saveSuccessful, saveFailed);
		};

		ctrl.updateContinueSubmit = function() {
			var messages = [];
			var msg1 = validateClassiFi(ctrl, true);
			if (msg1) messages.push(msg1);
			if (messages && messages.length > 0) {
				modalService.openErrorDialogs({
					'messages' : messages
				});
				return;
			}
			return authService.updateContinueSubmit(ctrl.classification).then(submitSuccessful, submitFailed);
		};

		ctrl.updateContinueCancel = function() {
			modalService.openConfirmDialogs({
				'messages' : [ {msg : 'title.dialog.confirm.cancel', args : [ctrl.classification.primaryKey]} ],
				'btnCallback' : {
					'ok' : function() {
						authService.updateContinueCancel(ctrl.classification).then(cancelSuccessful, cancelFailed);
					}
				}
			});
		};

		function submitSuccessful(response) {
			modalService.openAcknowledgeDialogs({
				'messages' : [ 'title.dialog.successful.submit' ],
				'btnCallback' : {
					'close' : function() {
						$scope.go('cda.workflow.wfSetup.list');
					}
				},
				'redirections' : [ {
					'name' : 'title.infobar.workflow.list',
					'state' : 'cda.workflow.wfSetup.list',
					'params' : {}
				}, {
					'name' : 'title.infobar.classification.list',
					'state' : 'cda.classification.list',
					'params' : {}
				}]
			});
		}

		function submitFailed(response) {
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}

		function saveSuccessful(response) {
			modalService.openInfoDialogs({
				'messages' : [ 'title.dialog.successful.save' ]
			});
			if (response.data && response.data.model) {
				ctrl.classification = response.data.model;
			}
			if (response.data.task && response.data.task.taskId) {
				authService.saveSuccessfulProcess(response.data.task).then(function(response) {
					var routerInfo = response.data || {}, state = routerInfo.processState;
					delete routerInfo.processState;
					$scope.go(state, routerInfo);
				}, angular.noop);
			}
		}

		function saveFailed(response) {
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}
		
		function cancelSuccessful(response) {
			modalService.openAcknowledgeDialogs({
				'messages' : [ 'title.dialog.successful.cancel' ],
				'btnCallback' : {
					'close' : function() {
						$scope.go('cda.workflow.wfSetup.list');
					}
				},
				'redirections' : [ {
					'name' : 'title.infobar.workflow.list',
					'state' : 'cda.workflow.wfSetup.list',
					'params' : {}
				}, {
					'name' : 'title.infobar.classification.list',
					'state' : 'cda.classification.list',
					'params' : {}
				}]
			});
		}

		function cancelFailed(response) {
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}
	}
})(angular);
